package com.kfm.jdbc.day0403;

import java.io.Serializable;

public class Demo07 {

    public static void main(String[] args) {
        /*
         浅拷贝和深拷贝
            浅拷贝：引用数据类型拷贝的是对象的地址。
            深拷贝：引用数据类型拷贝的是对象的内容。
          实现方式：
           实现 Cloneable 接口，重写 clone() 方法。

         */
        Computer computer = new Computer();
        computer.name = "联想";
        computer.price = 5000.0;
        Cpu cpu = new Cpu();
        cpu.name = "i7-7700";
        computer.cpu = cpu;

        System.out.println(computer);

        // 浅拷贝实现
//        Computer clone = null;
//        try {
//            clone = computer.clone();
//
//            clone.cpu.name = "i7-8700";
//        } catch (CloneNotSupportedException e) {
//            throw new RuntimeException(e);
//        }

        // 深拷贝实现
        Computer clone;
        try {
            clone = computer.clone();
            System.out.println(clone);

            clone.cpu.name = "i7-8700";
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }

        System.out.println(clone);
        System.out.println(computer);

    }
}


class Cpu implements Cloneable, Serializable {

    public String name;
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return super.toString() + "{" +
                "name='" + name + '\'' +
                '}';
    }
}

class Computer implements Cloneable, Serializable {

    public Cpu cpu;

    public String name;

    public Double price;

    @Override
    public String toString() {
        return super.toString() + "{" +
                "cpu=" + cpu +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    @Override
    protected Computer clone() throws CloneNotSupportedException {
        // 默认实现是浅拷贝
//        return (Computer) super.clone();
        // 深拷贝
        Computer clone = (Computer) super.clone();
        // 把 cpu（对象中的引用数据类型） 拷贝一份
        clone.cpu = (Cpu) this.cpu.clone();
        return clone;
    }
}
